package com.zw.commons.security.custom;/*
 *@program:java-cloud-prevalence
 *@author:zw
 *@Time: 2022/12/10
 *@description: UserDeteils自定义实现类
 */

import com.zw.api.LogFeignClient;
import com.zw.api.SystemFeignClient;
import com.zw.api.UserFeignClient;
import com.zw.commons.utlis.IpUtil;
import com.zw.object.system.SysUser;
import com.zw.object.vo.LogLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private SystemFeignClient systemFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userFeignClient.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (user.getStatus() == 0) {
            throw new RuntimeException("用户被禁用");
        }
        List<String> userPermsList = systemFeignClient.findUserPermsListToFeign(user.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perm : userPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }

        return new CustomUser(user, authorities);
    }
}
